package com.atguigu.srb.core.controller.api;


import com.alibaba.fastjson.JSON;
import com.atguigu.srb.base.util.JwtUtils;
import com.atguigu.srb.core.hfb.RequestHelper;
import com.atguigu.srb.core.result.R;
import com.atguigu.srb.core.service.UserAccountService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Map;

/**
 * <p>
 * 用户账户 前端控制器
 * </p>
 *
 * @author AtLong
 * @since 2022-06-11
 */
@RestController
@Api(tags = "用户账户管理")
@RequestMapping("/api/core/userAccount")
@Slf4j
public class WebUserAccountController {
    @Autowired
    private UserAccountService userAccountService;

    @GetMapping("/auth/getAccount")
    public R getAccount(HttpServletRequest request){
        // 从head中获取Token,并对token进行校验,确保用户已经登录,并从token中获取userId
        String token = request.getHeader("token");
        Long userId = JwtUtils.getUserId(token);
        BigDecimal account = userAccountService.getAccount(userId);
        log.info("获取账户余额用户的userId"+userId,"账户余额="+account);
        return R.ok().data("account",account);
    }

    /**账户充值
     * @return
     */
    @PostMapping("/auth/commitCharge/{chargeAmt}")
    public R commitCharge(@PathVariable("chargeAmt") BigDecimal chargeAmt, HttpServletRequest request) {
        // 从head中获取Token,并对token进行校验,确保用户已经登录,并从token中获取userId
        String token = request.getHeader("token");
        Long userId = JwtUtils.getUserId(token);

        // 根据userId进行账户绑定
        String formStr = userAccountService.commitCharge(chargeAmt, userId);

        return R.ok().data("formStr", formStr);
    }


    // 尚融宝回调接口
    //异步回调
    //（1）账户金额更改
    //（2）添加交易流水
    @ApiOperation(value = "用户账户充值异步回调接口")
    @PostMapping("/notify")
    public String asyncNotify(HttpServletRequest request) {
        // 获取汇付宝先srb发起回调的请求参数
        Map<String, String[]> requestParameterMap = request.getParameterMap();
        Map<String, Object> paramMap = RequestHelper.switchMap(requestParameterMap);
        log.info("账户充值的回调接收参数如下:" + JSON.toJSONString(paramMap));
        // 校验签名 ,校验状态码
        if (!RequestHelper.isSignEquals(paramMap) || !"0001".equals(paramMap.get("resultCode"))) {
            return "fail";
        }
        return userAccountService.notifyUserAccount(paramMap);

    }


}

